package com.sunnada.edu.system.upload.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.Common;
import com.sunnada.edu.system.pub.common.CommonException;
import com.sunnada.edu.system.pub.common.Constants;
import com.sunnada.edu.system.pub.common.FileUpload;
import com.sunnada.edu.system.pub.common.Plupload;
import com.sunnada.edu.system.pub.util.DateUtil;
import com.sunnada.edu.system.upload.dao.UploadDao;

@Service
@Transactional
public class UploadServiceImpl implements UploadService {
	@Resource
	UploadDao ploadDao;

	@Override
	public int getUploadCots(HashMap<String, String> params) {
		return ploadDao.getUploadCots(params);
	}

	@Override
	public List<?> findUpload(HashMap<String, String> params) {
		return ploadDao.findUpload(params);
	}

	public String materialUpload(Plupload plupload, HashMap<String, String> param) {
		HashMap<String, String> params = new HashMap<String, String>();
		String recId = Common.getSeqId("");
		// String recId ="2122";
		FileUpload upload = new FileUpload();
		upload.upload(plupload);
		File tempFile = plupload.getUploadFile();
		if (tempFile != null) {
			// 文件夹命名用时间格式
			SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
			// 临时文件路径
			String storePath = tempFile.getAbsolutePath();
			// 临时文件名
			String storeName = tempFile.getName();
			// 不同类型文件配置的存放路径
			String fileConfigPath = "";
			// 物理根目录
			/**************************
			 * 数据库配置（tomcat下server.xml 要配置虚拟路径 <Context
			 * docBase="C:/home/nmedia_ss_dev/upload" path="/nmedia/upload" />）
			 **************************/
			String date = DateUtil.getNowDate();
			String rootPath = AppContext.getInstance().getRootPath() + "/upload" + "/" + date;
			/***************
			 * 真实路径：docBase="C:/home/nmedia_ss_dev/upload"
			 * 虚拟路径：path="/nmedia/upload"
			 ****************************************************************/
			/* 判断是有有文件夹 */
			File file = new File(rootPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			// 获取上传文件的类型
			String fileType = getFileType(storeName, storePath);
			if (Constants.ELEMENT_TYPE1.equals(fileType)) {
				storeName = getFileName(storeName) + ".avi"; // 视频文件统一被转码成avi
			}
			// 将临时文件复制到对应目录下
			InputStream in = null;
			OutputStream out = null;
			try {
				out = new BufferedOutputStream(new FileOutputStream(new File(rootPath + "/" + storeName)), 2048);
				in = new BufferedInputStream(new FileInputStream(tempFile), 2048);
				byte[] buffer = new byte[2048];
				int len = 0;
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				params.put("recId", recId);
				params.put("materialName", plupload.getFileName());
				params.put("fileName", storeName);
				params.put("filePath", "/upload" + "/" + date + "/" + storeName);
				params.put("loginUserId", param.get("loginUserId"));
				params.put("fileSize",getFileSizeMegaBytes(tempFile));
				uploadAdd(params);
			} catch (Exception e) {
				CommonException.setException("上传出错，请联系系统管理员！");
			} finally {
				if (null != in) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (null != out) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			// 删除临时文件
			tempFile.delete();
		}
		return recId;
	}

	@Override
	public String uploadDel(HashMap<String, String> params) {
		List l = findUploadById(params);
		String msg = "";
		for (int i = 0; i < l.size(); i++) {
			HashMap<String, String> h = (HashMap<String, String>) l.get(i);
			String path = h.get("FILE_PATH");
			File file = new File(AppContext.getInstance().getRootPath() + path);
			if (file.exists()) { // 不存在返回 false
				file.delete();
			}
		}
		int t = ploadDao.uploadDel(params);
		if (t == 0) {
			msg = "删除失败";
		}
		return msg;
	}

	private String getFileType(String fileName, String filePath) {
		String fileType = "";
		String suffix = getFileSuffix(fileName).toLowerCase();
		if (Constants.VIDEO_SUFFIX.indexOf(suffix) >= 0 || Constants.AUDIO_SUFFIX.indexOf(suffix) >= 0) {
			fileType = Constants.ELEMENT_TYPE1;
		} else if (Constants.IMAGE_SUFFIX.indexOf(suffix) >= 0) {
			fileType = Constants.ELEMENT_TYPE2;
		}
		/*
		 * if (fileType == null || "".equals(fileType)) {
		 * CommonException.setException("上传文件格式不符合！"); }
		 */
		return fileType;
	}

	/**
	 * explain 获取文件后缀名
	 * 
	 * @param fileName
	 *            文件全名 aa.jpg
	 * @return String 后缀 jpg
	 */
	private String getFileSuffix(String fileName) {
		String t[] = fileName.split("\\.");
		if (t.length > 1) {
			return t[t.length - 1].toLowerCase();
		} else {
			return "";
		}
	}

	/**
	 * explain 获取文件名
	 * 
	 * @author niujs 2014-12-11 update niujs 2014-12-11
	 * @param fileName
	 *            文件全名 aa.jpg
	 * @return String 文件名 aa
	 */
	private String getFileName(String fileName) {
		String t[] = fileName.split("\\.");
		return t[0];
	}

	@Override
	public int uploadAdd(HashMap<String, String> params) {
		return ploadDao.uploadAdd(params);
	}

	@Override
	public List<?> findUploadById(HashMap<String, String> params) {
		return ploadDao.findUploadById(params);
		
	}

	public String getFileSizeMegaBytes(File file) {
		DecimalFormat   df   =   new   DecimalFormat("######.##");   
        return df.format((double) file.length()/(1024*1024))+" mb";
    }
}
